<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Transaction
 *
 * @author josema
 */
class TransactionUI extends SystemInterface implements Actionable {

    public function serviceHandler($vars){

        /*if($vars[0] == 'add')
            $action = 'add';
        else if ($vars[0] == 'showAllTransactions')
            $action = 'showAllTransactions';
*/
        return $this->runService($vars[0]);
    }

    protected function service_showAllTransactions(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        $user = $manager->getCurrentUser();

        $accounts = $user->getRelation('accounts');



        $transactions = $user->getRelation('transactions');

        $tpl = new Template();

        $tpl->add('interface_alias', 'transactions');

        $tpl->addObjects('accounts', $accounts);
        $tpl->addObjects('transactions', $transactions);

        $arr = array();
        foreach ($transactions as $obj){
            $arr [] = $obj->toArray();
        }

        return $tpl->fetch('jqgrid.tpl');
        //$dbf = new DataBaseFactory(new Transaction);

       /* $dbf->selectAllObjects();
        $tpl = new Template();

        while ($obj = $dbf->fetch()){
            $tpl->add('description',$obj->description);
            $tpl->add('amount',$obj->amount);

            print_r($obj->getRelation('owner'));
        }

        return $tpl->fetch('prueba.tpl');*/
    }

    protected function service_getTransactions(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        $user = $manager->getCurrentUser();

        $transactions = $user->getRelation('transactions');

        $tpl = new Template();

        require_once Path::getPath('libraries').'Grid.php';
        $grid = new Grid();

        return $grid->getJSON($transactions);

        $arr = array();
        foreach ($transactions as $obj){
            $arr [] = $obj->toArray();
        }
        return json_encode($arr);
    }

    protected function service_add(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        $user = $manager->getCurrentUser();

        $tr = new Transaction();

        // Submit one transaction
        $tr->formLoad();
        $tr->owner = $user->id;
        $tr->formatAmount();
        $tr->save();

        // Submit N transactions
        $i = 0;
        while($tr->formLoad(false, '_'.$i++)){
            $tr->owner = $user->id;

            $tr->formatAmount();
            
            $tr->save();
        }

        return $this->runService('showAllTransactions');
        
    }

    protected function service_showForm(){
        $tr = new Transaction();
        //$tmp = array(6927, 6928);

        $inner_form = false;
        //for ($i = 0; $i < count($tmp); $i++){
            //$tr->load($tmp[$i]);

            $inner_form .= $tr->showForm(false, false, '_0'/*.$i*/);
        //}

        $template = new Template();
        $template->add('inner_html', $inner_form);
        $template->add('action', 'add');
        return $template->fetch('form_inner_wrap.tpl');
        

    }

    protected function service_showImportForm(){
        $user = get_user();

        $tpl = new Template();

        $accounts = $user->getRelation('accounts');

        $tpl->add('action', 'import');
        $tpl->addObjects('accounts', $accounts);

        return $tpl->fetch('import_form.tpl');
    }

    protected function service_import(){
        if ($_FILES["file"]["error"] > 0)
          {
          echo "Error: " . $_FILES["file"]["error"] . "<br />";
          }
        else
          {
          echo "Upload: " . $_FILES["file"]["name"] . "<br />";
          echo "Type: " . $_FILES["file"]["type"] . "<br />";
          echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
          echo "Stored in: " . $_FILES["file"]["tmp_name"];

          $fd = fopen($_FILES["file"]["tmp_name"], 'r');
          $inner_form = '';

          $i = 0;
          while (($data = fgetcsv($fd, 1000, ";")) !== FALSE) {
                 // Algorithm to import from BCJ
                if(count($data) == 10)
                $arr = array_combine(array('date', 'fecha_valor', 'oficina', 'description',
               'gasto', 'currency', 'ingreso', 'currency_2', 'balance', 'currency_3'),
                       $data);
                else if(count($data) == 9)
                $arr = array_combine(array('date', 'fecha_valor', 'oficina', 'description',
               'gasto', 'currency', 'ingreso', 'currency_2', 'balance'),
                       $data);

                $tr = new Transaction($arr,
                    array('date', 'description', 'amount', 'type', 'label', 'account'));

                $tr->amount = (float)str_replace(',', '.',str_replace('.', '', $arr['ingreso']))
                        - (float)str_replace(',', '.',str_replace('.', '', $arr['gasto']));
                //@todo change, por ahora lo dejo por defecto a la cuenta de BCJ
                $tr->account = Input::get('account');
                // @todo, transfer and refound
                $tr->type = ($tr->amount > 0? 'Income': 'Expense');
                $tr->date = date_format(DateTime::createFromFormat('d-m-Y', $tr->date), "Y-m-d");

                $tr->label = get_label_for_description($tr->description);
                // If not amount, this is not a transaction
                if($tr->amount == 0)
                    continue;

                $inner_form .= $tr->showForm(false, false, '_'.$i++);


          }
          
          fclose($fd);

            $template = new Template();
        $template->add('inner_html', $inner_form);
        $template->add('action', 'add');
        return $template->fetch('form_inner_wrap.tpl');
          }
    }

    protected function service_getTimeLineChartData () {
        require Path::getPath('libraries') . 'Set.php';
        // Get current user
        $user = get_user();

        // Get all accounts initial amount
        $accounts = $user->getRelation('accounts');
        $acc_set = new Set ($accounts);
        $amount = $acc_set->sum ('initial_amount');

        /**Get from and limit date.
         * @todo this should be from the date of the first transaction to the today date
         */
        $from = new DateTime(Input::get('from_date'));
        $to = clone $from;
        $to->add (new DateInterval('P1M'));
        $limit = new DateTime();
        
        $result = array();
        while ($from < $limit) {
            // get transactions for this period
            $dbf = new DataBaseFactory(new Transaction);
            $transactions = $dbf->getWhere(array ('*'),
                    'owner = ' . $user->id .
                    " AND date >= '" . $from->format ('Y-m-d') . "'" .
                    " AND date < '" . $to->format ('Y-m-d') . "'");

            // add total amount for this period to the before amount
            $set = new Set($transactions);
            $amount += $set->sumWhereAttrNE('amount', 'type', 'Transfer');
            $income = $set->sumWhereAttrEQ('amount', 'type', 'Income');
            $expense = $set->sumWhereAttrEQ('amount', 'type', 'Expense');

            // add this to the array in the correct format
            //Formato : [new Date(2008, 1 ,1), 30000, undefined, undefined, 40645, undefined, undefined]
            $result [] = array ("new Date({$from->format('Y,m,d')})", 
                    $income, null, null, abs($expense), null, null, $amount, null, null);

            // Prepare for next iteration
            $from->add (new DateInterval('P1M'));
            $to->add (new DateInterval('P1M'));
        }

        // Return json of $result
        return json_encode($result);
    }

    protected function service_getChartData(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        $user = $manager->getCurrentUser();

        // Get transactions for current date range
        $dbf = new DataBaseFactory(new Transaction);
        $transactions = $dbf->getWhere(array ('*'), 
                'owner = ' . $user->id .
                " AND date >= '" . Input::get('from_date') . "'" .
                " AND date < '" . Input::get('to_date') . "'");

        // Create an array with labels as indexs and amount as value
        $tmp = array();
        foreach ($transactions as $trans){
            if($trans->type != 'Income' && $trans->type != 'Transfer') {
                if(key_exists($trans->label, $tmp))
                    $tmp[$trans->label] += $trans->amount;
                else
                    $tmp[$trans->label] = $trans->amount;
            }
        }

        // Order by amount
        asort($tmp);

        // Create JSON specific format for google pie chart visualization
        $result = array();
        $i = 0;
        $max_items = 7;
        $others = 0;
        foreach ($tmp as $key => $value) {
            // Get float value
            $float_value = (float) $value;

            // We are getting Expenses
            if ($float_value < 0) {
                // Just show $max_items and the rest as Others
                if ($i++ < $max_items)
                    $result[] = array($key, $float_value);
                else
                    $others += $float_value;
            }
        }
        // Show the rest as Others
        if ($others < 0)
            $result [] = array ('Others', $others);

        // Return JSON
        return json_encode($result);
    }

    protected function service_importCSV(){
        //Accion solo para importar la primera vez desde buxfer
        return false;
        
        $user = $this->getLoggedUser();

        $row = 1;
        if (($handle = fopen("/home/josema/Descargas/Cuentas/work.csv", "r")) !== FALSE) {
            echo "Fichero abierto";
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                $arr = array_combine(array('date', 'description', 'currency',
                    'amount', 'type', 'label', 'account', 'status'), $data);
                $num = count($data);
                echo "<p> $num fields in line $row: <br /></p>\n";
                $row++;
                for ($c=0; $c < $num; $c++) {
                    echo $data[$c] . "<br />\n";
                }
                $transaction = new Transaction($arr,
                    array('date', 'description', 'amount', 'type', 'label', 'account'));
                // Ponemos el propietario de la transaccion
                $transaction->owner = $user->id;
                // Modificacion de la cuenta, asocio ID
                $account_mapping = array('Efectivo' => 3, 'B. Principal' => 1, 'B. Poli' => 2, 'B. Dima' => 4);
                if($transaction->type == 'Transfer'){
                    list($from, $to) = explode('->', $transaction->account);
                    $transaction->account = trim($from);
                    $transaction->going_to = $account_mapping[trim($to)];
                }
                $transaction->account = $account_mapping[$transaction->account];
                // Paso la cantidad a entero
                $transaction->amount = str_replace(',', '', $transaction->amount);
                list(,$transaction->amount) = explode('+', $transaction->amount);
                // Pongo el simbolo a la cantidad
                $transaction->amount = ($transaction->type == 'Expense' || $transaction->type == 'Transfer')?
                        -$transaction->amount: $transaction->amount;
                $transaction->save();
                print_r($transaction);
                //if($row > 120) exit();
            }
            fclose($handle);
        }
        else echo "Fallo al abrir el fichero";
    }

    private function getLoggedUser(){
        require_once Path::getPath('users').'UserManager.php';
        $manager = new UserManager();

        return $manager->getCurrentUser();
    }
}
?>
